#include "loginwindow.h"
#include "getinfo.h"
#include <stdlib.h>
#include <qdebug.h>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>

Login::Login(QWidget *parent) : QDialog(parent)
{
    usrNum        = new int(0);
    isCorrect     = new int(0);
    msg           = new QLabel("请输入用户名和密码");msg->setAlignment(Qt::AlignHCenter);
    usrname       = new QLabel("用户名");
    passwd        = new QLabel("密码");
    input_usrname = new QLineEdit(this);
    input_passwd  = new QLineEdit(this);
    login         = new QPushButton("登录");
    cancel        = new QPushButton("取消");
    initLayout();
    usrinfo=getUsrInfo(usrNum);
    connect(this->login,&QPushButton::clicked,this,&Login::checkLogin);
    connect(this->cancel,&QPushButton::clicked,this,&Login::close);
    connect(this,&Login::loginSuccess,this,&Login::close);
    connect(this,&Login::loginFailure,this,[this](){msg->setText("用户名或密码错误");});
}
void Login::initLayout()
{
    this->setFixedSize(300,250);
    QWidget* w1=new QWidget();
    QWidget* w2=new QWidget();
    QWidget* w3=new QWidget();
    QGridLayout* g1=new QGridLayout();
    QHBoxLayout* g2=new QHBoxLayout();
    QHBoxLayout* g3=new QHBoxLayout();
    QVBoxLayout* g4=new QVBoxLayout();
    g1->addWidget(usrname,0,0,1,1);g1->addWidget(input_usrname,0,1,1,1);
    g1->addWidget(passwd,1,0,1,1);g1->addWidget(input_passwd,1,1,1,1);
    w1->setLayout(g1);
    g2->addWidget(msg);
    w2->setLayout(g2);
    g3->addWidget(login);g3->addWidget(cancel);
    w3->setLayout(g3);
    g4->addWidget(w1);g4->addWidget(w2);g4->addWidget(w3);
    this->setLayout(g4);
}

void Login::checkLogin()
{
    *isCorrect=0;
    QString Susrname=input_usrname->text();
    char* usrname=qstring2Char(Susrname);
    QString Spasswd=input_passwd->text();
    char* passwd=qstring2Char(Spasswd);
    for(int i=0;i<usrNum[0];i++)
    {
        if(strcmp(usrname,usrinfo[i][0])==0&&strcmp(passwd,usrinfo[i][1])==0)
        {
            *isCorrect=1;
        }
    }
    if(*isCorrect==1)
    {
        emit this->loginSuccess();
        accept();
    }
    else
        emit this->loginFailure();
}
